var crypto = require('crypto'); //加密库
var settings = require('../../settings'); //设置信息
var xml2js = require('xml2js');  //XML解析库

//接受weChat通知 接口

//微信get验证
exports.get = function(req,res){

	//认证
	console.log('微信公众平台开发者模式GET请求验证');
	var signature = req.param('signature');
	var timestamp = req.param('timestamp');
	var nonce = req.param('nonce');
	if (verification(signature,timestamp,nonce)) {
		res.send(req.param('echostr'));
	} else {
		console.log('微信发来的消息验证不成功')
		res.send(null);
	}
}



//微信post数据
exports.post = function(req,res){

	//认证
	console.log('微信公众平台开发者模式POST请求验证');
	var signature = req.param('signature');
	var timestamp = req.param('timestamp');
	var nonce = req.param('nonce');
	if (verification(signature,timestamp,nonce)) {
		var postDataStr = [];
		var size = 0;
		req.on('data', function(chunk) {
			postDataStr.push(chunk)
			size += chunk.length
		})
		req.on('end', function() {
			var buf = Buffer.concat(postDataStr, size);
			var str = iconv.decode(buf, 'utf8');
			xml2js.parseString(str, {
					explicitArray: false
				}, function(err, result) {
					console.log('微信发来的消息', result)
					if (err) {
						console.log('微信发来的消息解析不成功', err)
						return res.end()
					}
				});
			res.send(null);
		});
	} else {
		console.log('微信发来的消息验证不成功')
		res.send(null);
	}
}


//验证函数
function verification(signature,timestamp,nonce){
	var token = settings.token;
	var tmp = [token, timestamp, nonce].sort().join('');
	var shasum = crypto.createHash('sha1');
	shasum.update(tmp);
	var shaVal = shasum.digest('hex');
	return signature === shaVal;
}